<template>
  <el-form ref="login" class="login-form verify-code-form" :model="formData" @validate="onValidate">
    <el-form-item
      prop="phone"
      :rules="[
        { required: true, message: '请输入手机号' },
        {
          pattern: /^1\d{10}$/,
          message: '请输入手机号',
          trigger: ['blur', 'change'],
        },
      ]"
    >
      <LimitInput
        v-model.trim="formData.phone"
        numb
        clearable
        prefix-icon="el-icon-user"
        placeholder="请输入手机号"
        :maxlength="11"
      ></LimitInput>
    </el-form-item>
    <el-form-item
      class="verify-code-item"
      prop="code"
      :rules="[{ required: true, message: '请输入验证码' }]"
    >
      <LimitInput
        v-model.trim="formData.code"
        numb
        prefix-icon="el-icon-lock"
        placeholder="请输入验证码"
        @keyup.enter.native="handleSubmit"
      >
      </LimitInput>
      <el-button
        class="get-code"
        size="small"
        :disabled="getCodeDisabled"
        type="primary"
        @click="getCodeClick"
      >
        {{ countDownStarted ? `验证码(${codeCountDownNumb})` : '获取验证码' }}
      </el-button>
    </el-form-item>
    <el-button
      style="width: 100%"
      :disabled="disabled"
      class="login-btn"
      type="primary"
      @click="handleSubmit"
    >
      确定
    </el-button>
  </el-form>
</template>
<script>
export default {
  data() {
    return {
      formData: {
        phone: '',
        code: '',
      },
      valided: {
        phone: false,
        code: false,
      },
      codeCountDownNumb: 60,
      countDownStarted: false,
    };
  },
  computed: {
    disabled() {
      return !this.valided.phone || !this.valided.code;
    },
    getCodeDisabled() {
      return !this.valided.phone || this.countDownStarted;
    },
  },
  methods: {
    handleSubmit() {
      !this.disabled && this.$emit('submit', this.formData);
    },
    onValidate(valid, suc) {
      this.valided[valid] = suc;
    },
    //获取验证码
    getCodeClick() {
      if (!this.countDownStarted) {
        this.startCountDown();
        this.$api('getVerifyCode', this.formData)
          .then(res => {
            this.$message.success('验证码已发送，请注意查收');
          })
          .catch(e => {
            this.$message.warning('验证码发送失败');
            clearInterval(this.loop);
            this.countDownStarted = false;
          });
      }
    },
    startCountDown() {
      clearInterval(this.loop);
      this.countDownStarted = true;
      this.loop = setInterval(() => {
        this.codeCountDownNumb -= 1;
        if (this.codeCountDownNumb <= 0) {
          this.codeCountDownNumb = 60;
          clearInterval(this.loop);
          this.countDownStarted = false;
        }
      }, 1000);
    },
  },
};
</script>
<style lang="less" scoped>
.verify-code-form {
  .verify-code-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
    .get-code {
      width: 100px;
      flex: 0 0 auto;
    }
  }
}
</style>
